

const userModel = require('../lib/user.js');
const articleModel = require('../lib/article.js');
const moment = require('moment');

exports.getHome = async ctx => {
  await ctx.render('home', {
      session: 'a',
  })
}
exports.postLogin = async ctx => {
  let { name,password } = ctx.request.body
  await userModel.findDataByName(name)
    .then(result => {
        let res = result
        if (res.length && name === res[0]['name'] && password === res[0]['pass']) {
            // ctx.session = {
            //     user: res[0]['name'],
            //     id: res[0]['id']
            // }
            ctx.body = {
                code: 200,
                message: '登录成功'
            }
            console.log('登录成功')
        } else {
            ctx.body = {
                code: 500,
                message: '用户名或密码错误'
            }
            console.log('用户名或密码错误!')
        }
    }).catch(err => {
        console.log(err)
    })
}

exports.articleList = async ctx => {
    ctx.body = {
        code: 200,
        message: '登录成功',
        data:[{name:'文章1'}]
    }
}
exports.getArticle = async ctx => {
    await ctx.render('setArticle', {
        session: ctx.session,
    })
}
exports.setArticle = async ctx => {
    let { name,content } = ctx.request.body
    await articleModel.findArticleByName(name)
        .then(async result => {
            let res = result
            if (res.length && name === res[0]['name']) {
                
                ctx.body = {
                    code: 500,
                    message: '文章名已存在'
                }
                console.log('文章名已存在')
            } else {
                var result2 = await articleModel.insertData([name, content, moment().format('YYYY-MM-DD HH:mm:ss')])
                console.log('result2',result2)
                if(result2){
                    ctx.body = {
                        code: 200,
                        message: '文章保存成功'
                    }
                }
            }
        }).catch(err => {
            console.log(err)
        })
}
exports.getArticleList = async ctx => {
    var result = await articleModel.findArticle()
    console.log('result',result)
    if(result.length){
        ctx.body = {
            code: 200,
            message: '获取成功',
            data:{
                data:result
            }
        }
    }else{
        ctx.body = {
            code: 400,
            message: '失败',
        }
    }
}
